<?php

namespace App\Http\Controllers\Shop;

use Illuminate\Http\Request;

use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    /**
     * 商品列表  
     */
    public function getList(Request $request)
    {
        $keywords = $request->input('keywords');
        //读取店铺的id
        $sid = session()->get('sname')['id'];
        // dd($keywords);die;
        if(empty($keywords)){
            $goods = DB::table('goods')->where('sid','=',$sid)->paginate(10); 
        }else{
            $goods = DB::table('goods')->where('sid','=',$sid)->where('spname','like','%'.$keywords.'%')->paginate(10);
        }
        return view('Shop.goods.list',['goods'=>$goods,'data'=>$request->all()]);
    }

    /**
     * 商品添加 
     * 
     * @return \Illuminate\Http\Response
     */
    public function getAdd(Request $request)
    {
        //获取商品的分类
        $cates = $this->getAllCates();
        //获取所有品牌
        $branks = DB::table('branks')->get();
        //获取店铺的id
        $sid = session()->get('sname')['id'];
        return view('Shop.goods.add',['sid'=>$sid,'cate'=>$cates,'branks'=>$branks]);
    }
    /**
     * 执行添加
     */
    public function postDoadd(Request $request)
    {
        $data = $request->except(['_token','path']);
        if($request -> hasFile('cover')){
            //创建文件的名字
            $filename = time().rand(10000,99999);
            //获取文件的后缀
            $suffix = $request->file('cover')->getClientOriginalExtension();
            //上传路径
            $dirname = './uploads/shop/';
            //文件名
            $name = $filename.'.'.$suffix;
            //上传头像
            $request->file('cover')->move($dirname,$name);
            //
            $data['cover'] = trim($dirname.$name,'.');
        }
        $gid = DB::table('goods')->insertGetId($data);
        if(!$gid){
            return back();
        }
        if($request->hasFile('path')){
            $data =[];
            foreach($request->file('path')as $k => $v){
                $temp = [];
                $temp['goods_id'] = $gid;
                //定义文件夹位置
                $filename = time().rand(10000,99999);
                //获取文件的后缀
                $suffix = $v->getClientOriginalExtension();
                //上传路径
                $dirname = './uploads/goods/';
                //文件名
                $name = $filename.'.'.$suffix;
                //上传头像
                $v->move($dirname,$name);
                //
                $temp['path'] = trim($dirname.$name,'.');
                //压入到data中
                $data[] = $temp;

            }
            $res = DB::table('goods_imgs')->insert($data);
            if($res){
                return redirect('/goods/list')->with('info','添加成功');
            }else{
                return back()->with('info','添加失败');
            }

        }
        return redirect('/goods/list')->with('info','插入成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 显示修改页面
     */
    public function getEdit($id)
    {
        //
         //获取所有品牌
        $branks = DB::table('branks')->get();
        $cates = $this->getAllCates();
        $goods = DB::table('goods')->where('id','=',$id)->get()[0];
        return view('Shop.goods.edit',['goods'=>$goods,'cate'=>$cates,'branks'=>$branks]);
    }
    /**
     * 商品的修改
     */
    public function postDupdate(Request $request, $id)
    {
        $data = $request->except(['_token','path']);
        if($request -> hasFile('cover')){
            //创建文件的名字
            $filename = time().rand(10000,99999);
            //获取文件的后缀
            $suffix = $request->file('cover')->getClientOriginalExtension();
            //上传路径
            $dirname = './uploads/shop/';
            //文件名
            $name = $filename.'.'.$suffix;
            //上传头像
            $request->file('cover')->move($dirname,$name);
            //
            $data['cover'] = trim($dirname.$name,'.');
        }
        $gid = DB::table('goods')->where('id',$id)->update($data);
        if(!$gid){
            return back();
        }
        
        if($request->hasFile('path')){
            //获取原来的图片
            $img = DB::table('goods_imgs')->where('goods_id',$id)->get();
            foreach($img as $v){
                $aa = $v->path;
                @unlink('.'.$aa);
            }
            DB::table('goods_imgs')->where('goods_id',$id)->delete();
            $arr =[];
            foreach($request->file('path')as $k => $v){
                $temp = [];
                $temp['goods_id'] = $id;
                //定义文件夹位置
                $filename = time().rand(10000,99999);
                //获取文件的后缀
                $suffix = $v->getClientOriginalExtension();
                //上传路径
                $dirname = './uploads/goods/';
                //文件名
                $name = $filename.'.'.$suffix;
                //上传头像
                $res = $v->move($dirname,$name);

                //
                $temp['path'] = trim($dirname.$name,'.');
                //压入到data中
                $arr[] = $temp;
                

            }
            
            $res = DB::table('goods_imgs')->insert($arr);
            if($res){
                return redirect('/goods/list')->with('info','添加成功');
            }else{
                return back()->with('info','添加失败');
            }

        }
        return redirect('/goods/list')->with('info','插入成功');
    }

    /**
     * ajax请求改变商品状态
     */
    public function getUpdate(Request $request)
    {
        $id = $request->id;
        $status = $request->only(['status']);
        $res = DB::table('goods')->where('id','=',$id)->update($status);
        if($res){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 改变商品是否热销
     */
    public function getUpdatehot(Request $request)
    {
        $id = $request->id;
        $status = $request->only(['hot']);
        $res = DB::table('goods')->where('id','=',$id)->update($status);
        if($res){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 删除商品
     * @return \Illuminate\Http\Response
     */
    public function getDelete($id)
    {
        //获取商品信息
        $goods = DB::table('goods')->where('id','=',$id)->first();
        $cover = $goods->cover;
        //删除商品主图片
        @unlink('.'.$cover);
        $goods_imgs = DB::table('goods_imgs')->where('goods_id','=',$id)->get();
        // dd($goods_imgs);die;
        foreach($goods_imgs as $v){
            @unlink('.'.$v->path);
        }
        $res = DB::table('goods')->where('id','=',$id)->delete();
        if($res){
            return redirect('/goods/list')->with('info','删除成功');
        }else{
            return back()->with('info','删除失败');
        }
    }

    private function getAllCates()
    {
        //读去所有分类信息
        $cates = DB::table('cates')
            ->select(DB::raw('*,concat(path,",",id)as paths'))
            ->orderBy('paths')
            ->get();

        //格式化显示信息
        $cates = $this->formatCateInfo($cates);

        return $cates;
    }
    /**
     * 数据处理,格式化显示信息
     */
    private function formatCateInfo($cates)
    {
        foreach($cates as $k=>$v){
            $arr = explode(',', $v->path);
            $level = count($arr) -1;

            $v->name = str_repeat('|-----',$level). $v->name;
        }
        return $cates;
    }
}
